package com.dpad.crmclientapp.android.modules.newapp.ui.fragment

import android.Manifest
import android.app.Activity.RESULT_OK
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.imageloader.ILFactory
import cn.droidlover.xdroidmvp.imageloader.ILoader
import cn.droidlover.xdroidmvp.kit.Kits
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.dpad.crmclientapp.android.AppConstants
import com.dpad.crmclientapp.android.MainApplicaton
import com.dpad.crmclientapp.android.R
import com.dpad.crmclientapp.android.base.basecopy.BaseCopyFragment
import com.dpad.crmclientapp.android.data.http.ApiConstants
import com.dpad.crmclientapp.android.modules.cddd.activity.CDDDActivity
import com.dpad.crmclientapp.android.modules.ckbg.activity.CKBGActivity
import com.dpad.crmclientapp.android.modules.dczz.activity.DczzActivity
import com.dpad.crmclientapp.android.modules.internet_of_vehicles.activity.FinalDriveActivity
import com.dpad.crmclientapp.android.modules.internet_of_vehicles.bean.HomeCarDataBean
import com.dpad.crmclientapp.android.modules.internet_of_vehicles.bean.TitleToCode
import com.dpad.crmclientapp.android.modules.internet_of_vehicles.bean.XTSListEntity
import com.dpad.crmclientapp.android.modules.jyfw.activity.HistoryRescueActivity
import com.dpad.crmclientapp.android.modules.jyfw.activity.RescueActivity
import com.dpad.crmclientapp.android.modules.llcx.activity.LlcxActivity2
import com.dpad.crmclientapp.android.modules.newapp.bean.*
import com.dpad.crmclientapp.android.modules.newapp.event.CarChangeEvent
import com.dpad.crmclientapp.android.modules.newapp.presenter.UserCenterDetailPresenter
import com.dpad.crmclientapp.android.modules.newapp.ui.activity.ChargingActivity
import com.dpad.crmclientapp.android.modules.newapp.ui.activity.HomeActivity
import com.dpad.crmclientapp.android.modules.newapp.ui.activity.NewWebViewActivity
import com.dpad.crmclientapp.android.modules.newapp.ui.activity.UserDocumentActivity
import com.dpad.crmclientapp.android.modules.newapp.ui.adapter.UserCenterDetailAdapter
import com.dpad.crmclientapp.android.modules.sz.activity.SettingActivity
import com.dpad.crmclientapp.android.modules.t_activation.activity.TChooseCarActivity3
import com.dpad.crmclientapp.android.modules.t_activation.activity.WebViewCarActivity
import com.dpad.crmclientapp.android.modules.tsfx.activity.JXSActivity
import com.dpad.crmclientapp.android.modules.wdac.activity.AddMyCarActivity
import com.dpad.crmclientapp.android.modules.wxby.kt_activity.ReservationHomeActivity
import com.dpad.crmclientapp.android.modules.xcjl.activity.XcjlActivity2
import com.dpad.crmclientapp.android.modules.yy.activity.BookingActivity
import com.dpad.crmclientapp.android.modules.zpcx.activity.ZPCXActivity
import com.dpad.crmclientapp.android.modules.zpcx.activity.ZxingActivity
import com.dpad.crmclientapp.android.util.DataStatisticsUtils
import com.dpad.crmclientapp.android.util.PopupMenuUtil
import com.dpad.crmclientapp.android.util.PreferenceUtils
import com.dpad.crmclientapp.android.util.utils.*
import com.dpad.crmclientapp.android.widget.RecyclerViewDivider
import com.dpad.telematicsclientapp.adapter.UserCenterDetailAdapter
import com.dpad.telematicsclientapp.android.R
import com.dpad.telematicsclientapp.entity.UserCenterOnclick
import com.dpad.telematicsclientapp.event.CarChangeEvent
import com.dpad.telematicsclientapp.mvp.event.BusProvider
import com.dpad.telematicsclientapp.mvp.imageloader.ILFactory
import com.dpad.telematicsclientapp.mvp.imageloader.ILoader
import com.dpad.telematicsclientapp.mvp.kit.Kits
import com.dpad.telematicsclientapp.netlibrary.AppConstants
import com.dpad.telematicsclientapp.netlibrary.Contances
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyFragment
import com.dpad.telematicsclientapp.netlibrary.http.ApiConstants
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.*
import com.dpad.telematicsclientapp.ui.HomeActivity
import com.dpad.telematicsclientapp.util.DataStatisticsUtils
import com.dpad.telematicsclientapp.util.PreferenceUtils
import com.dpad.telematicsclientapp.util.TitleToCode
import com.dpad.telematicsclientapp.util.utils.*
import com.dpad.telematicsclientapp.utils.PopupMenuUtil
import com.dpad.telematicsclientapp.weiget.RecyclerViewDivider
import com.socks.library.KLog
import com.tbruyelle.rxpermissions2.RxPermissions
import com.yzq.zxinglibrary.bean.ZxingConfig
import kotlinx.android.synthetic.main.fragment_detail_usercenter.*
import rx.subscriptions.CompositeSubscription
import java.util.*
import com.flyco.roundview.RoundTextView

/**
 * ================================================
 * 作    者：wenbody
 * 版    本：1.0
 * 创建日期：2019/12/31 16:04
 * 描    述：
 * 修订历史：
 * ================================================
 */
class UserCenterDetailFragment : BaseCopyFragment<UserCenterDetailPresenter>(), BaseQuickAdapter.OnItemClickListener, View.OnClickListener, PopupMenuUtil.OnItemCheckedChange {


    lateinit var userCenterAdapter: UserCenterDetailAdapter
    var data = mutableListOf<UserCenterMoudle>()
    lateinit var callBack: UserCenterOnclick

    private var ntspAppUserinfo: UserCenterVo.Result.NtspAppUserinfo? = null

    private var vehinfosBeans: ArrayList<HomeCarDataBean.ResultBean.VehinfosBean>? = null

    private var cityCode: String = ""
    private var lng: String = ""
    private var lat: String = ""
    private var phone: String = ""

    private var plateNumber = ""
    private var showVin = true
    var showCharingButton:String="1" //1显示充电桩按钮，0不显示  默认显示 用来记录是否显示寻找充电桩按钮的

    override fun initPageData() {
        userIcon.setOnClickListener(this)
        userNickName.setOnClickListener(this)
        userTag.setOnClickListener(this)
        userCenterGoto.setOnClickListener(this)
        settingIm.setOnClickListener(this)
        myCarRl.setOnClickListener(this)
        changeCar.setOnClickListener(this)
        addMyCarRl.setOnClickListener(this)
        cityCode = PreferenceUtils.getInstance(context).getString("cityCode")
        lng = PreferenceUtils.getInstance(context).getString("longitude")
        lat = PreferenceUtils.getInstance(context).getString("latitude")

        userCenterRv.layoutManager = GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, false)
        userCenterRv.addItemDecoration(RecyclerViewDivider(context, RecyclerViewDivider.BOTH_SET, UIUtils.dip2px(10), UIUtils.getColor(R.color.transparency)))
        userCenterAdapter = UserCenterDetailAdapter(data)
        userCenterRv.adapter = userCenterAdapter
        userCenterAdapter.bindToRecyclerView(userCenterRv)
        userCenterAdapter.onItemClickListener = this

        callBack = context as HomeActivity
        changFragment.setOnClickListener {
            DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE171.title, System.currentTimeMillis().toString(), Constant.NOMAL))
            callBack.changeUserCenter(false)
        }
        loadPIc()
    }


    override fun useEventBus(): Boolean {
        return true
    }

    override fun getLayout(): Int {
        return R.layout.fragment_detail_usercenter
    }

    override fun newPresenter(subscriptions: CompositeSubscription?): UserCenterDetailPresenter {
        return UserCenterDetailPresenter()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        var intent: Intent
        MainApplicaton.pageType = 1
        when (data[position].clickPosition) {
            0 -> {//充电订单
                intent = Intent(context, CDDDActivity::class.java)
            }
            1 -> {//救援记录
                //DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE135.title, System.currentTimeMillis().toString() , Constant.NOMAL))
                intent = Intent(context, HistoryRescueActivity::class.java)



            }
            2 -> {//预约记录
                //DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE136.title, System.currentTimeMillis().toString() , Constant.NOMAL))
//                intent = Intent(context, BookingActivity::class.java)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_BOOKING, Contances.GROUP_YUYUE)
                        .navigation(context)

            }
            3 -> {//环保驾驶
                //DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE163.title, System.currentTimeMillis().toString() , Constant.NOMAL))
//                intent = Intent(context, FinalDriveActivity::class.java)
//                intent.putExtra("tag","2")

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_HUANBAO, Contances.GROUP_HUANBAO)
                        .withString("tag","2")
                        .navigation(context)

            }
            4 -> {//爱车追踪
//                intent = Intent(context, DczzActivity::class.java)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_DCZZ, Contances.GROUP_DAOCHE)
                        .navigation(context)

            }
            5 -> {//流量查询
                //DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE131.title, System.currentTimeMillis().toString() , Constant.NOMAL))
//                intent = Intent(context, LlcxActivity2::class.java)
//                intent.putExtra("vin", MainApplicaton.vin)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_LLCX, Contances.GROUP_LLCX)
                        .withString("vin", MainApplicaton.vin)
                        .navigation(context)

            }
            6 -> {//维保预约
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE97.title, System.currentTimeMillis().toString() + "", Constant.NOMAL))
//                intent = Intent(context, ReservationHomeActivity::class.java)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_WBYY, Contances.GROUP_WBYY)
                        .navigation(context)

            }
            7 -> {//紧急救援
//                intent = Intent(context, RescueActivity::class.java)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_JJJY, Contances.GROUP_JJJY)
                        .navigation(context)

            }
            8 -> {//车况报告
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE63.title, System.currentTimeMillis().toString() , Constant.NOMAL))
//                intent = Intent(context, CKBGActivity::class.java)
//                intent.putExtra("tag","2")

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_CKBG, Contances.GROUP_CKBG)
                        .withString("tag","2")
                        .navigation(context)


            }
            9 -> {//寻找充电桩
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE99.title, System.currentTimeMillis().toString(), Constant.NOMAL))
                intent = Intent()
                intent.action = "android.intent.action.VIEW"
                val content_url = Uri.parse("https://qr.alipay.com/s6x04082xwqdvjzamu795ad")
                intent.data = content_url
            }
            10 -> {//经销商查询
//                intent = Intent(context, JXSActivity::class.java)
//                intent.putExtra("tag","2")

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_JXS, Contances.GROUP_HOME)
                        .withString("tag", "2")
                        .navigation(context)


            }
            11 -> {//备件查询
                val rxPermissions = RxPermissions(context)
                rxPermissions
                        .request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA)
                        .subscribe { aBoolean ->
                            DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE144.title, System.currentTimeMillis().toString() , Constant.GO_IN))
                            if (aBoolean) {
//                                val intent1 = Intent(context, ZxingActivity::class.java)
                                /*ZxingConfig是配置类
                                 *可以设置是否显示底部布局，闪光灯，相册，
                                 * 是否播放提示音  震动
                                 * 设置扫描框颜色等
                                 * 也可以不传这个参数
                                 * 设置扫描线的颜色，只需要在Zxing包下的drawable文件夹里替换扫描线文件即可
                                 * */
                                val config = ZxingConfig()
                                config.isPlayBeep = false//是否播放扫描声音 默认为true
                                config.isShake = true//是否震动  默认为true
                                config.isDecodeBarCode = true//是否扫描条形码 默认为true
                                config.reactColor = R.color.color_6DC6DA//设置扫描框四个角的颜色 默认为淡蓝色
                                config.isFullScreenScan = true//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
//                                intent1.putExtra(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, config)
//                                startActivityForResult(intent1, 1122)

                                ARouter.getInstance()
                                        .build(Contances.URL_ACTIVITY_Zxing, Contances.GROUP_ZPCX)
                                        .withSerializable(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, config)
                                        .navigation(context,1122)


                                return@subscribe
                            } else {
                                val title = UIUtils.getString(R.string.dialog_warning_title)
                                val content = UIUtils.getString(R.string.permission_camera_error)
                                DialogUtil.showPermissionSettingDialog(context, title, content) { dialog: Dialog, confirm: Boolean ->
                                    if (confirm) { //跳转系统权限设置界面
                                        val packageURI = Uri.parse("package:" + context.packageName)
                                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                                        this.startActivityForResult(intent, Constant.STARTACTIVITY_PREMISSION)
                                        dialog.dismiss()
                                    }
                                }
                                return@subscribe
                            }
                        }
                return
//                intent = Intent(context, ZPCXActivity::class.java)
            }
            12 -> {//行程记录
//                intent = Intent(context, XcjlActivity2::class.java)
//                intent.putExtra("tag","2")


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_XCJL, Contances.GROUP_XCJL)
                        .withString("tag","2")
                        .navigation(context)

            }
            13 -> {//预约试驾
                val url = ApiConstants.getAppYysjUrl() +
                        "&cityCode=" + cityCode +
                        "&lng=" + lng +
                        "&lat=" + lat +
                        "&carTypeCode=default"+
                        "&brandCode=" + AppConstants.BRANDCODE
//                intent = Intent(context, NewWebViewActivity::class.java)
//                intent.putExtra(Constant.WEBVIEWKEY, url)
//                intent.putExtra(Constant.WEBVIEW_TITLE_KEY, "预约试驾")

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_NEWWEBVIEW, Contances.GROUP_OTHER)
                        .withString(Constant.WEBVIEWKEY, url)
                        .withString(Constant.WEBVIEW_TITLE_KEY, "预约试驾")
                        .navigation(context)

            }
            else -> {
                return
            }
        }
//        context.startActivity(intent)
    }

//    override fun getPageTitle(): String {
//        return "个人中心详细页"
//    }

    override fun visiableLoadData() {
        p.getxiaotieshi()//判断充电桩按钮是否显示的
        initFloatButton()
        if (MainApplicaton.sIsLogin) {
            loadData(false)
            loadPIc()
        }

    }

    //充电桩按钮是否显示返回的结果
    public fun chongdianzhuang(bean: XTSListEntity){
        if (!Kits.Empty.check(bean)) {
            if (bean.code == "00000") {

                if (bean.result.size > 0) {
                    if (!Kits.Empty.check(bean.result[0].codeValue)) {
                        if (bean.result[0].codeValue == "0") {//1显示充电桩按钮，0不显示
//                            llCdz.setVisibility(View.GONE)//充电桩按钮
                            showCharingButton="0"
                        } else {
//                            llCdz.setVisibility(View.VISIBLE)//充电桩按钮
                            showCharingButton="1"
                        }
                    }
                }


            }

        }
    }


    private fun initFloatButton() {
        val y: Float = if (Kits.Empty.check(PreferenceUtils.getInstance(context).getString(FLOATBUTTON_POSITION_KEY))) UIUtils.dip2px(150).toFloat() else PreferenceUtils.getInstance(context).getString(FLOATBUTTON_POSITION_KEY).toFloat()
        val isAlign = PreferenceUtils.getInstance(context).getString(FLOATBUTTON_IS_ALIGN_LEFT_KEY)
        changFragment.setLocation(isAlign, y)
    }

    override fun onClick(v: View?) {
        val intent: Intent
        when (v?.id) {
            R.id.userTag, R.id.userNickName, R.id.userIcon, R.id.userCenterGoto -> {//个人资料
                if (ntspAppUserinfo != null) {
//                    intent = Intent(context, UserDocumentActivity::class.java)
//                    intent.putExtra(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)


                    ARouter.getInstance()
                            .build(Contances.URL_ACTIVITY_USERDOCUMENT, Contances.GROUP_OTHER)
                            .withObject(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
                            .navigation(context)

                } else {
                    return
                }
//                intent = Intent(context, UserDocumentActivity::class.java)
            }
            R.id.settingIm -> {//设置
                intent = Intent(context, SettingActivity::class.java)
                intent.putExtra(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
            }
            R.id.myCarRl -> {//我的爱车
                //DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE137.title, System.currentTimeMillis().toString() , Constant.NOMAL))
//                intent = Intent(context, TChooseCarActivity3::class.java)
//                intent.putExtra("type", "1")


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_TChooseCar, Contances.GROUP_MYCAR)
                        .withString("type", "1")
                        .navigation(context)

            }
            R.id.changeCar -> {//切换爱车
                vehinfosBeans?.let { showCarList(it) }
                return
            }
            R.id.addMyCarRl -> {//添加爱车
//                intent = Intent(context, AddMyCarActivity::class.java)
                intent = Intent(context, WebViewCarActivity::class.java)
                intent.putExtra("type", "0")//添加爱车跳H5传0，自助激活跳H5传1
                intent.putExtra("vin", MainApplicaton.vin)




            }
            else -> {
                return
            }
        }
        startActivity(intent)
    }

    /**
     * 加载数据
     */
    fun loadData(needLoadImage: Boolean) {
        val sortedMap: SortedMap<String, Any> = sortedMapOf(
                Pair("currentPage", 1),
                Pair("pageSize", 20),
                Pair("data", UserCenterEntry("", "", MainApplicaton.userVehType, MainApplicaton.vin)))
        p.getUserData(sortedMap, needLoadImage)
        p.getVersionMessage(mainmessageicon);
    }

    fun showData(value: UserCenterVo) {

        ntspAppUserinfo = value.result.ntspAppUserinfo
        value.result.ntspAppUserinfo?.let { saveToSp(it) }

        if (value.result.listLabel != null) {
            initFunctionData(value.result.listLabel!!)
        }

        userTag.text = if (!Kits.Empty.check(value.result.ntspAppUserinfo?.label)) value.result.ntspAppUserinfo?.label.toString() else "编辑标签"
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_TAG, if (!Kits.Empty.check(value.result.ntspAppUserinfo?.label)) value.result.ntspAppUserinfo?.label.toString() else "")
        if (value.result.appFavoriteRsDtos != null && value.result.appFavoriteRsDtos!!.isNotEmpty()) {
            carName.text = getCarNameByVin(MainApplicaton.vin, value.result.appFavoriteRsDtos)
            addMyCarRl.visibility = View.GONE
            changeCar.visibility = View.VISIBLE
            if (showVin) {
                userCenterPlateLocation.visibility = View.GONE
                userCenterPlateNumber.visibility = View.GONE
                userCenterVin.visibility = View.VISIBLE
                userCenterVin.text = plateNumber
            } else {
                userCenterPlateLocation.visibility = View.VISIBLE
                userCenterPlateNumber.visibility = View.VISIBLE
                userCenterVin.visibility = View.GONE
                userCenterPlateLocation.text = plateNumber.substring(0, 1)
                userCenterPlateNumber.text = plateNumber.substring(1, plateNumber.length)
            }

            if (vehinfosBeans == null) {
                vehinfosBeans = arrayListOf()
            } else {
                vehinfosBeans!!.clear()
            }
            for (item in value.result.appFavoriteRsDtos!!) {
                val vehinfosBean = HomeCarDataBean.ResultBean.VehinfosBean()
                vehinfosBean.vin = item.vin
                vehinfosBean.plateNumber = item.plateNumber
                vehinfosBean.isChecked = item.vin == MainApplicaton.vin
                vehinfosBean.userVehType = if (item.userVehType.isNullOrEmpty()) "" else item.userVehType
                vehinfosBean.saleSubmodelId = item.saleSubmodelId
                vehinfosBean.linePic = item.pic
                vehinfosBean.settState(item.tState)
                vehinfosBeans!!.add(vehinfosBean)
            }
        } else {
            addMyCarRl.visibility = View.VISIBLE
            changeCar.visibility = View.GONE
            carName.text = "我的爱车"
        }
        userNickName.text = if (!Kits.Empty.check(value.result.ntspAppUserinfo?.nickName)) value.result.ntspAppUserinfo?.nickName else value.result.ntspAppUserinfo?.loginName
        val options = ILoader.Options(R.mipmap.default_user_im, R.mipmap.default_user_im)
        if (!Kits.Empty.check(ntspAppUserinfo?.picUrl)) {
            ILFactory.getLoader().loadNet(userIcon, ntspAppUserinfo!!.picUrl, options)
        } else {
            ILFactory.getLoader().loadResource(userIcon, R.mipmap.default_user_im, null)
        }

    }

    fun loadPIc() {
        if (!Kits.Empty.check(MainApplicaton.urlMap["populevehicle"])) {
            ILFactory.getLoader().loadNet(myCarIm, MainApplicaton.urlMap["populevehicle"], ImgUtil.getOptions(R.mipmap.xzcx_big1, R.mipmap.xzcx_big1))
        }else{
            myCarIm.setImageResource(R.mipmap.xzcx_big1)
        }
    }


    private fun saveToSp(ntspAppUserinfo: UserCenterVo.Result.NtspAppUserinfo) {
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_REALNAME, ntspAppUserinfo.realName)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_PHONE, ntspAppUserinfo.phone)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_NICKNAME, ntspAppUserinfo.nickName)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_SEX, ntspAppUserinfo.sex)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_BIRTHDAY, ntspAppUserinfo.birthday)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_PIC_URL, ntspAppUserinfo.picUrl)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_PROVINCE, ntspAppUserinfo.province)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_CITY, ntspAppUserinfo.city)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_ADDRESS, ntspAppUserinfo.address)
    }


    /**
     * 根据vin选择爱车名称
     */
    private fun getCarNameByVin(vin: String, appFavoriteRsDtos: List<UserCenterVo.Result.AppFavoriteRsDto>?): String {
        var name = "我的爱车"
        if (appFavoriteRsDtos != null && appFavoriteRsDtos.isNotEmpty()) {
            for (item in appFavoriteRsDtos) {
                /**
                 *  tState ，0:非T车辆，1:T车辆（已激活） ,  2:T车辆（未激活）
                 */
                if (vin == item.vin) {
                    if (!Kits.Empty.check(item.tState) && (item.tState == "1") || (item.tState == "0")) {
                        carZzjh.text = "查看更多"
                    } else {
                        carZzjh.text = "自助激活"
                    }
                    if (!Kits.Empty.check(item.plateNumber)) {
                        plateNumber = item.plateNumber!!
                        showVin = false
                    } else {
                        plateNumber = item.vin
                        showVin = true
                    }
                    if (!Kits.Empty.check(item.nikeName)) {
                        name = item.nikeName!!
                        return name
                    }
                    if (!Kits.Empty.check(item.carSysName)) {
                        name = item.carSysName!!
                        return name
                    } else {
                        name = "我的爱车"
                    }
                }
            }
        }
        return name
    }

    //弹出选择爱车的列表
    private fun showCarList(vehinfosBeans: List<HomeCarDataBean.ResultBean.VehinfosBean?>) {
        if (!Kits.Empty.check(vehinfosBeans) && vehinfosBeans.isNotEmpty()) {
            for (i in vehinfosBeans.indices) {
                vehinfosBeans[i]!!.isChecked = MainApplicaton.vin == vehinfosBeans[i]!!.vin
            }
            PopupMenuUtil.getInstance().top_show(context, detailUserCenterParent, vehinfosBeans, this)
        } else {
            T.showToastSafeError("未获取到车辆信息")
        }
    }

    /**
     * 切换爱车
     */
    override fun OnItemCheckedLister(index: Int) {
        if (vehinfosBeans != null) {
            if (checkTstatus(vehinfosBeans, index)) {
                DialogUtil.showBasicDialog(context, "", "车辆未激活", "取消", "去激活") { dialog, confirm ->
                    if (confirm) {
//                        val intent = Intent(context, TChooseCarActivity3::class.java)
//                        intent.putExtra("type", "1")
//                        startActivity(intent)

                        ARouter.getInstance()
                                .build(Contances.URL_ACTIVITY_TChooseCar, Contances.GROUP_MYCAR)
                                .withString("type", "1")
                                .navigation(context)


                    }
                    dialog.dismiss()
                }
            } else {
                MainApplicaton.vin = vehinfosBeans!![index].vin
                MainApplicaton.userVehType = vehinfosBeans!![index].userVehType
                MainApplicaton.setSaleSubmodelId(vehinfosBeans!![index].saleSubmodelId)
                if (!Kits.Empty.check(vehinfosBeans!![index].plateNumber)) {
                    MainApplicaton.setPlateNumber(vehinfosBeans!![index].plateNumber)
                } else {
                    MainApplicaton.setPlateNumber("")
                }
                loadData(true)
                BusProvider.getBus().post(CarChangeEvent(0, checkTstatus(vehinfosBeans, index)))
                val userLoginStateChangeEvent = UserLoginStateChangeEvent(MainApplicaton.sIsLogin, MainApplicaton.isTcar)
                BusProvider.getBus().post(userLoginStateChangeEvent)
            }


        }
    }

    /**
     * 确定当前爱车是否是未激活t车,未激活t车需要弹框
     */
    private fun checkTstatus(vehinfosBeans: ArrayList<HomeCarDataBean.ResultBean.VehinfosBean>?, index: Int): Boolean {
        if (vehinfosBeans == null || vehinfosBeans.isEmpty()) {
            return false
        } else {
            /**
             *  tState ，0:非T车辆，1:T车辆（已激活） ,  2:T车辆（未激活）
             */
            if (!Kits.Empty.check(vehinfosBeans[index].gettState()) && vehinfosBeans[index].gettState() == "2") {
                return true
            }
            return false
        }
    }

    /**
     * 处理功能按钮的数据
     */
    private fun initFunctionData(listLabel: List<UserCenterVo.Result.Label>) {
        data.clear()

        if (showCharingButton=="1"){//证明是需要显示寻找充电桩按钮的，此时不对数据进行处理
            for (item in listLabel) {
                data.add(UserCenterMoudle(item.codeName, UserCenterFunctionEnum.getClickPosition(item.codeName), UserCenterFunctionEnum.getImageResouse(item.codeName)))
            }
        }else{//证明不需要显示寻找充电桩按钮，此时要处理数据

                for (item in listLabel) {
                        if (item.codeName=="寻找充电桩"){//此时不添加
                            //不做处理
                        }else{
                            data.add(UserCenterMoudle(item.codeName, UserCenterFunctionEnum.getClickPosition(item.codeName), UserCenterFunctionEnum.getImageResouse(item.codeName)))
                        }
                }
        }

        userCenterAdapter.notifyDataSetChanged()
    }

//    override fun onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int): Animator? {
//        if (nextAnim != 0) {
//            val anim = AnimatorInflater.loadAnimator(context, nextAnim)
//            anim.addListener(object : AnimatorListenerAdapter() {
//                override fun onAnimationEnd(animation: Animator?) {
//                    super.onAnimationEnd(animation)
//                    initFloatButton()
//                    loadData()
//                }
//
////            override fun onAnimationStart(animation: Animator?) {
////                super.onAnimationStart(animation)
////            }
//            })
//            return anim
//        }
//        return null
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1122 && resultCode == RESULT_OK) {
            if (data != null) {
                val content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
                val intent = Intent(context, ZPCXActivity::class.java)
                intent.putExtra("number", content)
                context.startActivity(intent)
            }
        }

    }

    override fun isTFragment(): Boolean {
        return true
    }

    override fun getPageTitle(): String {
        return TitleToCode.TYPE94.title
    }
}